<?php

use App\Models\LoginLog;
use \Illuminate\Support\Facades\Log;
use App\Models\User;

/**
 * api请求返回格式化
 * @param int $code
 * @param array $data
 * @return array
 */
function jsonResponse($code = 20000, $data = [])
{
    if ($code == config('common.validatorError')) {
        $data = $data->errors()->getMessages();
    }
    $messages = config('errors');
    return [
        'code' => $code,
        'message' => $messages[$code],
        'data' => $data
    ];
}

/**
 * 记录登录日志
 * @param $user
 * @param $type
 * @param $agent
 */
function setLoginLog($user, $type, $agent = '')
{
    $log = new LoginLog();
    $log['user_id'] = $user['id'];
    $log['ip'] = $user['last_ip'];
    $log['time'] = $user['last_time'];
    $log['type'] = $type;
    $log['agent'] = $agent;
    $log->save();
}

/**
 * 检查用户登录状态
 * @param $request
 * @return bool
 */
function checkUserLoginStatus($request)
{
    $token = $request->header(config('common.tokenKey'));
    $user = User::where('token', $token)->first();
    if (empty($user)) {
        return false;
    } else {
        return $user;
    }
}
